package com.kucun.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.kucun.bean.Page;
import com.kucun.bean.Users;
import com.kucun.listener.OnlineSession;
import com.kucun.listener.SessionListener;
import com.kucun.service.Userservice;
import com.kucun.util.GetMAC;
import com.kucun.util.NetworkUtil;
import com.tgb.test.LogAfterAdvice;
import com.times.cache.Cache;
import com.times.util.DateUtils;
import net.sf.json.JSONObject;


@Controller
@RequestMapping("/users")
public class UsersController {
	private static final Logger logger = Logger.getLogger(LogAfterAdvice.class.getName());
	
	public static String userna;
	@Autowired
	private Userservice userservice;
	
	/**
	 * 获取用户列表
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/getallusers.html")
	public String getAllUser(int rows,int page,String cs,HttpServletRequest request,HttpServletResponse response) throws IOException{
		Page page1=new Page();
		page1.setI(rows*(page-1));
		page1.setRows(rows);
		page1.setObj(cs);
		System.out.println(page+","+rows);
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map  
		List<Users> list = userservice.findAll(page1);	
		jsonMap.put("total",userservice.getCount(cs).getTotal());//total键 存放总记录数，必须的  
        jsonMap.put("rows",list);//rows键 存放每页记录 list  
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);//格式化result   一定要是JSONObject  
        PrintWriter pw = response.getWriter();
        pw.write(jsonObject.toString());
		return null;
	}
	
	@RequestMapping("/queryusers.html")
	public String queryusers(String y,String s,int rows,int page,HttpServletRequest request,HttpServletResponse response) throws IOException{
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map  
		List<Users> list = userservice.query(""+y,""+s,rows*(page-1),rows);	
		jsonMap.put("total",userservice.queryCount(y, s).getTotal());//total键 存放总记录数，必须的  
        jsonMap.put("rows",list);//rows键 存放每页记录 list  
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);//格式化result   一定要是JSONObject  
        PrintWriter pw = response.getWriter();
        pw.write(jsonObject.toString());
		return null;
	}
	/**
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddUser.html")
	public String toAddUser(HttpServletRequest request){
		
		return "/addUser";
	}
	/**
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/addUser.html")
	public String addUser(Users user,HttpServletRequest request){
		userservice.save(user);
		return "redirect:/user/getAllUser.html";
	}
	
	/**
	 * @param user
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/updateuser.html")
	@ResponseBody    //spring 异常统一处理方式
	public void updateUser(Users user,HttpServletRequest request,HttpServletResponse response) throws IOException{
	    PrintWriter out = response.getWriter();
	    if (user.getUserid()!=null) {
	    	if(userservice.update(user)){
	  			out.write("ok");
	  		}else{
	  			out.write("error");
	  		}
		}else{
			if(userservice.save(user)){
	  			out.write("ok");
	  		}else{
	  			out.write("error");
	  		}
		}
	  
	}
	/**
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUser.html")
	public String getUser(int id,HttpServletRequest request){
		
		request.setAttribute("user", userservice.findById(id));
		return "/editUser";
	}
	/**
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delet.html")
	public void delUser(String id,HttpServletRequest request,HttpServletResponse response){
		String result = "{\"result\":\"error\"}";
		String string=id;
		if(userservice.delete(string)){
			result = "{\"result\":\"success\"}";
		}
		response.setContentType("application/json");
		try {
			PrintWriter out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	@SuppressWarnings("rawtypes")
	@RequestMapping("/login.html")
	public String login(Users users,HttpServletRequest request){
		String s="/login";
		HttpSession session=request.getSession(true);
		try {
			List sessions = SessionListener.getSessions();  
			logger.info("当前登录人数："+sessions.size());
			//验证是否是正版授权不是就只能登录5个用户
			 if(GetMAC.Md5(GetMAC.getServersMac()).equals(Cache.getProperty("sys.license"))){
								Users user1=userservice.login(users.getLogname());
								if (user1!=null&&users.getPassword().equals(user1.getPassword())&&user1.getIsused().equals("是")) {
									session.setAttribute("user",user1);
									s="/page/index";
									//记入session监听器
									session.setAttribute(SessionListener.LISTENER_NAME,new OnlineSession(request.getRemoteAddr(),users.getLogname(),new Date().toString()));
									logger.info("日期:["+DateUtils.getStringDate()+"]["+users.getLogname()+"] 登录成功！登录IP:["+NetworkUtil.getIpAddress(request)+"]");
								}else{
									request.setAttribute("msg", "用户名或密码错误！");
								}
			 }else{ 
				 int allowloginuser=4;	
							 if(sessions.size()<allowloginuser){
									Users user1=userservice.login(users.getLogname());
									if (user1!=null&&users.getPassword().equals(user1.getPassword())&&user1.getIsused().equals("是")) {
										session.setAttribute("user",user1);
										s="/page/index";
										//记入session监听器
										session.setAttribute(SessionListener.LISTENER_NAME,new OnlineSession(request.getRemoteAddr(),users.getLogname(),new Date().toString()));
										logger.info("日期:["+DateUtils.getStringDate()+"]["+users.getLogname()+"] 登录成功！登录IP:["+NetworkUtil.getIpAddress(request)+"]");
									}else{
										request.setAttribute("msg", "用户名或密码错误！");
									}
							}else{
									request.setAttribute("msg", "对不起！试用版最多只允许【"+allowloginuser+"】个用户同时登录系统！授权MAC："+GetMAC.getServersMac());
							}
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	@RequestMapping("/exit.html")
	public String clear(HttpServletRequest request){
		request.getSession(true).invalidate();
		return "/login";
	}
	@RequestMapping("/updateuserpassword.html")
	public void updateUserPassword(HttpServletRequest request,HttpServletResponse response) throws IOException{
	    PrintWriter out = response.getWriter();
	    String userid=request.getParameter("userid");
	    String password=request.getParameter("qrmm");
	    Users user=new Users();
	    user.setUserid(Integer.valueOf(userid));
	    user.setPassword(password);
	    	if(userservice.updateUserPassword(user)>0){
	  			out.write("ok");
	  		}else{
	  			out.write("error");
	  		}
	}
	/**
	 * 重写用户页面获取数据方法
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping("/getalluserinfo.html")
	public String getAllUserInfo(int rows,int page,HttpServletRequest request,HttpServletResponse response) throws IOException{
        String q=request.getParameter("q");
        //System.out.println("q="+q);
		String field=request.getParameter("field");
		
		if(q!=null){
			field="clientname";
		}
        String searchertext=request.getParameter("searchertext");
        if("".equals(searchertext)||searchertext==null){
        	searchertext=q;
        }else{
        	searchertext = URLDecoder.decode(searchertext, "utf-8");
        } 
		Page page1=new Page();
		page1.setI(rows*(page-1));
		page1.setRows(rows);
		page1.setFiled(field);
		page1.setSearchertext(searchertext);
		try {
			String a=request.getParameter("a");
			page1.setObj(a);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Map<String, Object> jsonMap = new HashMap<String, Object>(); 
		List<Users> list = userservice.GetAllUsers(page1);	
		jsonMap.put("total",userservice.getUsersCount(page1).getTotal());
        jsonMap.put("rows",list); 
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        PrintWriter pw = response.getWriter();
        pw.write(jsonObject.toString());
		return null;
	}
	
	/**
	 * @param user
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/addorupateuserinfo.html")
	@ResponseBody    //spring 异常统一处理方式
	public void addClientinfo(Users user,HttpServletRequest request,HttpServletResponse response) throws IOException{
		String tag=request.getParameter("tag");
		Integer s=0;
		String result = "{\"success\":\"false\"}";
		PrintWriter pw = response.getWriter();
		response.setContentType("application/json");
		if("1".equals(tag)){  //编辑用户信息
			int ss=userservice.updateByPrimaryKeySelective(user);
			if(ss>0){
				result = "{\"success\":\"true\"}";
			}else{
				result = "{\"success\":\"false\"}";
			}
		}else{
			user.setUserid(null);
			s=userservice.insertSelective(user);
			if(s>0){
				 result = "{\"success\":\"true\"}";		
			}else{
				result = "{\"success\":\"false\"}";
			}
		}
		pw.write(result);
	}
}
